﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace BuyTrainTicket
{
    public partial class Order : PhoneApplicationPage
    {
        string mdate;
        string mfromstation;
        string mtostation;
        string mtickettypes;
        string mpassenges;
        string mprefertrain;
        string mpreferstarttime;
        string mpreferarrivetime;
        string mbuyasmanyas;

        public Order()
        {
            InitializeComponent();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            DateTime dateTime = (DateTime)date.Value;
            mdate = dateTime.ToString("yyyy-MM-dd");
            mfromstation = fromstation.Text;
            mtostation = tostation.Text;
            mtickettypes = tickettypes.Text;
            mpassenges = passengers.Text;
            mprefertrain = prefertrain.Text;
            mpreferstarttime = preferstarttime.Text;
            mpreferarrivetime = preferarrivetime.Text;
            mbuyasmanyas = (bool)checkbuyasmanyas.IsChecked ? "true" : "false";

            if (mtickettypes == null || mtickettypes.Equals("") || mpassenges == null || mpassenges.Equals(""))
            {
                MessageBox.Show("请选择席别和购票人");
                return;
            }
            if (mprefertrain != null && !mprefertrain.Equals(""))
            {
                String pattern = "^([A-Z0-9]+(([A-Z0-9]*,)*[A-Z0-9]+)?)?$";
                Regex reg = new Regex(pattern);
                if (!reg.IsMatch(mprefertrain))
                {
                    MessageBox.Show("首先车次格式不对");
                    return;
                }
            }
            if (mpreferstarttime != null && !mpreferstarttime.Equals(""))
            {
                String pattern = "^((([0-1][0-9])|([2][0-3])):([0-5][0-9])-(([0-1][0-9])|([2][0-3])):([0-5][0-9]))(,((([0-1][0-9])|([2][0-3])):([0-5][0-9])-(([0-1][0-9])|([2][0-3])):([0-5][0-9])))*$";
                Regex reg = new Regex(pattern);
                if (!reg.IsMatch(mpreferstarttime))
                {
                    MessageBox.Show("出发时间格式不对");
                    return;
                }
            }
            if (mpreferarrivetime != null && !mpreferarrivetime.Equals(""))
            {
                String pattern = "^((([0-1][0-9])|([2][0-3])):([0-5][0-9])-(([0-1][0-9])|([2][0-3])):([0-5][0-9]))(,((([0-1][0-9])|([2][0-3])):([0-5][0-9])-(([0-1][0-9])|([2][0-3])):([0-5][0-9])))*$";
                Regex reg = new Regex(pattern);
                if (!reg.IsMatch(mpreferarrivetime))
                {
                    MessageBox.Show("到达时间格式不对");
                    return;
                }
            }

            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            string username;
            string password;
            settings.TryGetValue<String>("username", out username);
            settings.TryGetValue<String>("password", out password);
            if (username == null || password == null)
            {
                MessageBox.Show("请先设置用户名和密码");
                NavigationService.Navigate(new Uri("/Setting.xaml", UriKind.Relative));
                return;
            }

            settings["buydate"] = mdate;
            settings["buyfromstation"] = mfromstation;
            settings["buytostation"] = mtostation;
            settings["tickettypes"] = mtickettypes;
            settings["passengers"] = mpassenges;
            settings["prefertrain"] = mprefertrain;
            settings["preferstarttime"] = mpreferstarttime;
            settings["preferarrivetime"] = mpreferarrivetime;
            settings.Save();

            sendRequest(Util.host + "/servlet/Buy12306Servlet?action=order&password=" + password + "&username=" + username + "&type=order&version=8.1");

        }

        void sendRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.BeginGetRequestStream(new AsyncCallback(getRequestCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试1");

                });
            }
        }

        void getRequestCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                Stream postStream = request.EndGetRequestStream(asyncResult);

                StringBuilder postData = new StringBuilder();
                postData.Append("date=" + mdate + "&fromStation=" + mfromstation + "&toStation=" + mtostation + "&ticketType=" + mtickettypes + "&buyer=" + mpassenges + "&prefertrain=" + mprefertrain + "&preferstarttime=" + mpreferstarttime + "&preferarrivetime=" + mpreferarrivetime + "&buyasmany=" + mbuyasmanyas);

                byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());

                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试2");

                });
            }
        }

        void getResponseCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    byte[] byteArray = new byte[response.ContentLength];
                    response.GetResponseStream().Read(byteArray, 0, (int)response.ContentLength);
                    String responseStr = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                    JObject responseObj = JsonConvert.DeserializeObject<JObject>(responseStr);
                    JToken errMsgToken = responseObj.GetValue("errMsg");
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show((string)errMsgToken);
                    });

                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(response.StatusCode.ToString());
                    });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试3");

                });
            }
        }

        private void TextBox_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/SelectTicketType.xaml", UriKind.Relative));
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            String datestr;
            settings.TryGetValue<String>("buydate", out datestr);
            if (datestr != null)
            {
                DateTime dateTime = new DateTime(Convert.ToInt32(datestr.Substring(0, 4)), Convert.ToInt32(datestr.Substring(5, 2)), Convert.ToInt32(datestr.Substring(8, 2)));
                date.Value = dateTime;
            }
            String buyfromstationstr;
            settings.TryGetValue<String>("buyfromstation", out buyfromstationstr);
            if (buyfromstationstr != null)
            {
                fromstation.Text = buyfromstationstr;
            }
            String buytostationstr;
            settings.TryGetValue<String>("buytostation", out buytostationstr);
            if (buytostationstr != null)
            {
                tostation.Text = buytostationstr;
            }
            String tickettypestr;
            settings.TryGetValue<String>("tickettypes", out tickettypestr);
            if (tickettypestr != null)
            {
                tickettypes.Text = tickettypestr;
            }
            String passengersstr;
            settings.TryGetValue<String>("passengers", out passengersstr);
            if (passengersstr != null)
            {
                passengers.Text = passengersstr;
            }
            String prefertrainstr;
            settings.TryGetValue<String>("prefertrain", out prefertrainstr);
            if (prefertrainstr != null)
            {
                prefertrain.Text = prefertrainstr;
            }
            String preferstarttimestr;
            settings.TryGetValue<String>("preferstarttime", out preferstarttimestr);
            if (preferstarttimestr != null)
            {
                preferstarttime.Text = preferstarttimestr;
            }
            String preferarrivetimestr;
            settings.TryGetValue<String>("preferarrivetime", out preferarrivetimestr);
            if (preferarrivetimestr != null)
            {
                preferarrivetime.Text = preferarrivetimestr;
            }
        }

        private void passengers_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/SelectPassengers.xaml", UriKind.Relative));
        }
    }
}